from typing import List, Type, Optional, Tuple
from sqlalchemy.orm import Session
from schemas.delivery_person import CreateDeliveryPersonRequest, UpdateDeliveryPersonRequest
from db import models


class DeliveryPerson:
    @staticmethod
    def create(db: Session, data: CreateDeliveryPersonRequest) -> models.DeliveryPerson:
        item = models.DeliveryPerson(
            created_on=data.created_on,
            created_by=data.created_by,
            name=data.name,
            phone=data.phone,
        )
        db.add(item)
        db.commit()
        return item

    @staticmethod
    def get_all(db: Session) -> List[Type[models.DeliveryPerson]]:
        return db.query(models.DeliveryPerson).filter_by(status=1).all()

    @staticmethod
    def gets(db: Session,
             page: int,
             page_size: int,
             kw: Optional[str] = None) -> Tuple[int, list[Type[models.DeliveryPerson]]]:
        if kw is None:
            count = db.query(models.DeliveryPerson).filter_by(status=1).count()

            data = db.query(models.DeliveryPerson).filter_by(status=1).offset(page * page_size).limit(page_size).all()
        else:
            count = db.query(models.DeliveryPerson).filter_by(status=1).filter(
                models.DeliveryPerson.name.like(f"%{kw}%")
            ).count()

            data = db.query(models.DeliveryPerson).filter_by(status=1).filter(
                models.DeliveryPerson.name.like(f"%{kw}%")
            ).offset(page * page_size).limit(page_size).all()
        return count, data

    @staticmethod
    def update(db: Session, data: UpdateDeliveryPersonRequest) -> None:
        db.query(models.DeliveryPerson).filter_by(id=data.id).update({
            "name": data.name,
            "phone": data.phone,
            "updated_on": data.updated_on,
            "updated_by": data.updated_by
        })
        db.commit()

    @staticmethod
    def delete(db: Session, id_: int):
        db.query(models.DeliveryPerson).filter_by(id=id_).update({
            "status": 0,
        })
        db.commit()
